import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-08-13
 * Time: 22:16
 */
class User {
    public String username;
    public String password;

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

@WebServlet("/jsonParameter")
public class Test extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // 通过 post 请求的 body 传递过来一个 json 格式的字符串.
        // 1.使用objectMapper将json字符串解析成java对象
        User user = objectMapper.readValue(req.getInputStream(), User.class);
        resp.getWriter().write("1.使用objectMapper将json字符串解析成java对象:<br/>"+user.toString()+"<br/>");

        // 2.使用objectMapper将java对象解析成json字符串
        String jsonString = objectMapper.writeValueAsString(user);
        resp.getWriter().write("2.使用objectMapper将java对象解析成json字符串:<br/>"+jsonString);
    }
}
